/*
 * Copyright 2025 xclite.com and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.xclite.api.utils;

import org.ssssssss.script.MagicScript;
import org.ssssssss.script.MagicScriptContext;
import org.ssssssss.script.MagicScriptDebugContext;

import java.util.Map;

/**
 * 脚本管理
 *
 * @author zhixiulee
 */
public class ScriptManager {
    /**
     * 表达式前缀
     */
    private static final String EXPRESSION_PREFIX = "/* generated by execute expression */ return ";

    /**
     * 执行脚本
     */
    public static Object executeScript(String script, MagicScriptContext context) {
        script = (context instanceof MagicScriptDebugContext ? MagicScript.DEBUG_MARK : "") + script;
        MagicScript magicScript = MagicScript.create(script, null);
        // 执行脚本
        return magicScript.execute(context);
    }

    /**
     * 执行脚本
     */
    public static Object executeExpression(String script, MagicScriptContext context) {
        return executeScript(EXPRESSION_PREFIX + script, context);
    }

    /**
     * 执行脚本
     */
    public static Object executeExpression(String script, Map<String, Object> paramMap) {
        return executeExpression(script, new MagicScriptContext(paramMap));
    }
}
